import axios from 'axios'
import qs from 'qs'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth/token'
import { getCookieValue } from '@/utils/utils'
import router from '@/router'
import store from '@/store'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000, // request timeout
  paramsSerializer: params => {
    return qs.stringify(params, { arrayFormat: 'comma' })
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    addAuthorizationHeaders(config.headers);
    addAcceptLanguageHeader(config.headers);
    addTenantIdHeader(config.headers);
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

function addAuthorizationHeaders(headers) {
  const token = getToken();
  if (token && headers) {
    headers['Authorization'] = 'Bearer ' + token;
  }
}

function addAcceptLanguageHeader(headers) {
  const cookieLangValue = getCookieValue("localization_language");
  if (cookieLangValue && headers) {
    headers['Accept-Language'] = cookieLangValue;
  }
}

function addTenantIdHeader(headers) {
  const cookieTenantIdValue = getCookieValue('__tenant');
  if (cookieTenantIdValue && headers) {
    headers['__tenant'] = cookieTenantIdValue;
  }
}

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const data = response.data
    return data
  },
  error => {
    console.log('err', error) // for debug

    var statusCode = error.response.status;
    var statusText = error.response.statusText;
    const data = error.response.data
    var errorMessage = data.error && data.error.message || '';
    var errorDetail = data.error && data.error.detail || '';

    errorMessage = errorMessage + errorDetail
    if (statusCode === 400) {
      MessageBox.alert(errorMessage || "请求无效 (Bad request)", statusCode, { type: 'error' })
    } else if (statusCode === 401) {
      store.dispatch('auth/removeToken').then(() => {
        router.go(router.currentRoute);
      })
    } else if (statusCode === 403) {
      MessageBox.alert(errorMessage || "没有权限访问", statusCode, { type: 'error' })
    } else if (statusCode === 404) {
      MessageBox.alert(errorMessage || "请求资源不存在", statusCode, { type: 'error' })
    } else if (statusCode >= 500) {
      MessageBox.alert(errorMessage || statusText, statusCode, { type: 'error' })
    } else {
      MessageBox.alert(errorMessage || statusText, statusCode, { type: 'error' })
    }

    return Promise.reject(error)
  }
)

export default service
